package midi.midi;

import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import java.io.File;

/**
 * Midi文件播放器
 */
public class MidiPlayer extends Thread {
    String songFile;

    public MidiPlayer(String songName) {
        this.songFile = songName;
    }

    public static void play(String songFile) {

        new Thread(new MidiPlayer(songFile)).start();
    }

    public void run() {
        Sequence currentSound;// 音序
        Sequencer sequencer;// 默认音序器
        try {
            System.out.println(songFile);
            File file = new File(songFile);
            currentSound = MidiSystem.getSequence(file);
            sequencer = MidiSystem.getSequencer();
            sequencer.open();
            sequencer.setSequence(currentSound);
            sequencer.start();
            while (sequencer.isRunning()) {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
            }
            sequencer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}